package com.wzh.borrow.service.impl;

import com.wzh.borrow.dao.BorrowDao;
import com.wzh.borrow.dao.UserDao;
import com.wzh.borrow.entity.BorrowEntity;
import com.wzh.borrow.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzh.common.utils.PageUtils;
import com.wzh.common.utils.Query;

import com.wzh.borrow.dao.RefundDao;
import com.wzh.borrow.entity.RefundEntity;
import com.wzh.borrow.service.RefundService;


@Service("refundService")
public class RefundServiceImpl extends ServiceImpl<RefundDao, RefundEntity> implements RefundService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private BorrowDao borrowDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<RefundEntity> page = this.page(
                new Query<RefundEntity>().getPage(params),
                new QueryWrapper<RefundEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void add(RefundEntity refund) {
        //添加还款记录
        baseMapper.insert(refund);
        //修改借款记录
        BorrowEntity borrow = borrowDao.selectById(refund.getBid());
        borrow.setMoney(borrow.getMoney()-refund.getMoney());
        borrow.setRefunded(borrow.getRefunded()+ refund.getMoney());
        borrowDao.updateById(borrow);
        //给被借款人加钱
        UserEntity buser = userDao.selectById(refund.getBuid());
        buser.setMoney(buser.getMoney()+refund.getMoney());
        userDao.updateById(buser);
        //给借款人减钱
        UserEntity user = userDao.selectById(refund.getUid());
        user.setMoney(user.getMoney()-refund.getMoney());
        userDao.updateById(user);
        //判断是否还款完毕 修改状态
        if (borrow.getMoney()<=0){
            borrow.setState("还款完成");
            borrowDao.updateById(borrow);
        }
    }

}